$(document).ready(() => {

    let shopcart = JSON.parse(window.sessionStorage.getItem("shopcart"))
    let content = ''

    let cartTotalPrice = parseFloat(window.sessionStorage.getItem('cartTotalPrice')).toFixed(2);
    shopcart.forEach(item => {
        content += `<dd>
                        <div class="checkoutcart-tablerow">
                            <div class="cell itemname" title="${item.foodName}">${item.foodName}</div>
                                <div class="cell itemquantity">
                                    <input readonly value="${item.foodCount}" id="${item.foodId}" class="ng-pristine ng-valid">
                                </div>
                            <div class="cell itemtotal">${item.foodUnitPrice}</div>
                        </div>
                    </dd>`
    });
    $('#shopcarFoods').html(content)
    $('#totalPrice').text(cartTotalPrice)
})

function add(item) {
    console.log(item)
}

function sub(item) {
    console.log(item)
}

$('#changeAddress').on('click', () => {

    let user = JSON.parse(window.localStorage.getItem('user'))
    if (!user) {
        alert('User Un Login...')
        return;
    }

    $('#modal-container-524903').modal('show')
    let set = user.addressSet;
    console.log(set)

    let address = ''
    set.forEach(item => {
        console.log(item)
        address += `<li class="extra" style="width: 100%;background-color: #fcfaf8; line-height: 28px;font-size: 14px;color: #666; padding: 5px; line-height: 28px;">
                        <span id="r-name" style="margin: 0px;">${item.addressContactPerson}</span><br/>
                        <span id="r-tel" style="margin: 0px;">${item.addressContactTel}</span><br/>
                        <span id="r-address-name" style="margin: 0px;">${item.addressName}</span>
                        <span class="pull-right btn btn-default" onclick="selectAddress('${item.addressId}', '${item.addressContactPerson}', '${item.addressContactTel}', '${item.addressName}')">选择</span>
                    </li>
                    <hr/>`
    })

    address = '<ul>' + address + '</ul>'
    $('#addressList').html(address)
})

$('#place').on('click', () => {
    const serverHost = window.config.serverHost

    let user = JSON.parse(window.localStorage.getItem('user'))
    if (!user) {
        alert('User Un Login...')
        return;
    }
    let curretnAddressId = $('#addressId').val()
    if (!curretnAddressId) {
        alert('Please Select A Address..')
        return;
    }
    let p = $('#r-name').text();
    let t = $('#r-tel').text();
    let n = $('#r-address-name').text();
    if (p == '必填' || t == '必填' || n == '必填') {
        alert('Please Add A Address First!')
        return;
    }

    let shopcart = JSON.parse(window.sessionStorage.getItem('shopcart'))

    let addressId = $('#addressId').val()
    let customerId = JSON.parse(window.localStorage.getItem('user')).customerId
    let merchantId = window.sessionStorage.getItem('merchantId')
    let count = 1
    let orderFoods = []
    shopcart.forEach(item => {
        let order = {}
        order.foodId = item.foodId
        order.count = item.foodCount
        orderFoods.push(order)
    })

    console.log(addressId, customerId, merchantId, JSON.stringify(orderFoods))
    $.ajax({
        url: `${serverHost}/order/placeorder`,
        type: 'POST',
        data: {
            addressId: addressId,
            customerId: customerId,
            merchantId: merchantId,
            orderFoods: JSON.stringify(orderFoods),
        },
        success: data => {
            console.log(data)
            if (data.status == 'SUCCESS') {
                $('#placeResult').text(' Place Order Success!')
                $('#placeSuccess').modal('show')

                window.sessionStorage.removeItem('shopcart');
                window.sessionStorage.removeItem('cartTotalPrice');
                window.sessionStorage.removeItem('foodListSize');

                let ws = new WebSocket("ws://10.222.29.145:8880/acmsystem-m-v2.0/ordernew");
                ws.onopen = function (evt) {
                    ws.send("PLACE_SUCCESS");
                };

                ws.onmessage = function (evt) {
                    console.log("Received Message:" + evt.data);
                    ws.close();
                }

                ws.onclose = function (evt) {
                    console.log("Connection closed!");
                }
            } else {
                $('#placeResult').text('Place Order Fail. Please Try Again Latter.')
                $('#placeSuccess').modal('show')
            }
        },
        error: () => {
            $('#placeResult').text('Server Error. Please Try Again Latter.')
            $('#placeSuccess').modal('show')
        }
    })
})

$("#confirmOrder").on('click', () => {
    $('#placeSuccess').modal('hide')
    location.href = "./personal.html"
})

$('#address').on('click', () => {

})

function selectAddress(addressId, concatName, concatTel, addressName) {
    console.log(addressId, concatName, concatTel, address)

    $('#modal-container-524903').modal('hide')

    $('#r-name').text(concatName)
    $('#r-tel').text(concatTel)
    $('#r-address-name').text(addressName)

    $('#addressId').val(addressId)
}

function selectAddress(addressId, concatName, concatTel, addressName) {
    console.log(addressId, concatName, concatTel, address)

    $('#modal-container-524903').modal('hide')

    $('#r-name').text(concatName)
    $('#r-tel').text(concatTel)
    $('#r-address-name').text(addressName)

    $('#addressId').val(addressId)
}